<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划编码" prop="planCode">
        <el-input
          v-model="queryParams.planCode"
          placeholder="请输入计划编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['plan:plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['plan:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['plan:plan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['plan:plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划ID" align="center" prop="planId" />
      <el-table-column label="计划编码"  align="center" prop="planCode" >
        <template #default="scope">
          <!-- span包裹文本，加蓝色+hover加深效果 -->
          <span 
            style="color: #409EFF; cursor: pointer;"
            :style="{ 'hover': 'color: #1E88E5;' }"
            @click="viewDetail(scope.row)"
          >
            {{ scope.row.planCode }} <!-- 绑定计划编码数据 -->
          </span>
        </template>
      </el-table-column>
      <el-table-column label="计划名称" align="center" prop="planName" />
      <el-table-column label="计划类型" align="center" prop="planType" />
      <el-table-column label="开始日期" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="频率" align="center" prop="cycleType" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['plan:plan:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['plan:plan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备点检保养计划表对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="planRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="计划编码" prop="planCode">
          <el-input style="width: 250px;" v-model="form.planCode" placeholder="请输入计划编码" :disabled="value1"/>
          <el-switch v-model="value1"  @change="handleChange" />自动生成
          <el-form-item label="计划名称" prop="planName">
          <el-input style="width: 250px;" v-model="form.planName" placeholder="请输入计划名称" />
        </el-form-item>
        </el-form-item>
        
        <el-form-item label="计划类型" prop="planType">
          <el-select style="width: 250px;" v-model="form.planType" placeholder="请选择计划类型">
            <el-option label="设备保养计划" value="设备保养计划" />
            <!-- 可根据实际需求添加其他计划类型选项 -->
          </el-select>
          <el-form-item label="频率" prop="cycleType">
          <el-input-number v-model="form.cycleCount" :min="1" placeholder="请输入频率数值" style="width: 200px;" />
          <el-select v-model="form.cycleType" placeholder="请选择时间单位" style="width: 200px; margin-left: 10px;">
            <el-option label="小时" value="小时" />
            <el-option label="天" value="天" />
            <el-option label="周" value="周" />
            <el-option label="月" value="月" />
          </el-select>
        </el-form-item>
        </el-form-item>
        
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker style="width: 200px;"
            v-model="form.startDate"
            type="date"
            placeholder="选择开始日期"
            value-format="yyyy-MM-dd"
          />
          <el-form-item label="结束日期" prop="endDate">
          <el-date-picker style="width: 200px;"
            v-model="form.endDate"
            type="date"
            placeholder="选择结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select style="width: 200px;" v-model="form.status" placeholder="请选择状态">
            <el-option label="已完成" value="已完成" />
            <el-option label="进行中" value="进行中" />
            <el-option label="未开始" value="未开始" />
          </el-select>
        </el-form-item>
        </el-form-item>
        
        
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>

        <el-tabs v-model="activeTab" v-show="activeShow">
          <!-- 设备清单标签页 -->
          <el-tab-pane label="设备清单" name="deviceList">
            <Checkmachinery :current-planId="form.planId"/>
          </el-tab-pane>

          <!-- 保养项目标签页 -->
          <el-tab-pane label="保养项目" name="maintenanceItem">
            <CheckSubject :current-planId="form.planId"/>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button v-show="flag" type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备选择弹窗 -->
    <el-dialog title="设备选择" v-model="deviceSelectDialogVisible" width="1300px" append-to-body>
      <el-form :inline="true" :model="deviceSearchForm" class="device-search-form" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="deviceSearchForm.categoryName" placeholder="请输入分类名称" clearable />
        </el-form-item>
        <el-form-item label="设备编码">
          <el-input v-model="deviceSearchForm.deviceCode" placeholder="请输入设备编码" clearable />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="deviceSearchForm.deviceName" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchDevices">搜索</el-button>
          <el-button icon="Refresh" @click="resetDeviceSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-tree
        :data="deviceCategoryData"
        :props="treeProps"
        @node-click="handleDeviceCategoryClick"
        style="width: 200px; float: left; margin-right: 10px;"
      />
      <el-table :data="deviceSelectTableData" border style="width: calc(100% - 210px); float: left;" @selection-change="handleDeviceSelectSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="deviceCode" label="设备编码" />
        <el-table-column prop="deviceName" label="设备名称" />
        <el-table-column prop="brand" label="品牌" />
        <el-table-column prop="specModel" label="规格型号" />
        <el-table-column prop="workshop" label="所属车间" />
        <el-table-column prop="status" label="设备状态" />
        <el-table-column prop="createTime" label="创建时间" />
      </el-table>
      <div style="clear: both;"></div>
      <el-pagination
        @size-change="handleDeviceSelectSizeChange"
        @current-change="handleDeviceSelectCurrentChange"
        :current-page="deviceSelectCurrentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="deviceSelectPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="deviceSelectTotal"
        style="margin-top: 10px;"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deviceSelectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDeviceSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 项目选择弹窗 -->
    <el-dialog title="项目选择" v-model="itemSelectDialogVisible" width="1300px" append-to-body>
      <el-form :inline="true" :model="itemSearchForm" class="item-search-form" label-width="80px">
        <el-form-item label="项目编码">
          <el-input v-model="itemSearchForm.itemCode" placeholder="请输入项目编码" clearable />
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="itemSearchForm.itemName" placeholder="请输入项目名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchItems">搜索</el-button>
          <el-button icon="Refresh" @click="resetItemSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="itemSelectTableData" border style="width: 100%; margin-top: 10px;" @selection-change="handleItemSelectSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="itemCode" label="项目编码" />
        <el-table-column prop="itemType" label="项目类型" />
        <el-table-column prop="itemContent" label="项目内容" />
        <el-table-column prop="standard" label="标准" />
        <el-table-column prop="isEnabled" label="是否启用">
          <template #default="scope">
            <el-tag v-if="scope.row.isEnabled" type="success">是</el-tag>
            <el-tag v-else type="danger">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
      </el-table>
      <el-pagination
        @size-change="handleItemSelectSizeChange"
        @current-change="handleItemSelectCurrentChange"
        :current-page="itemSelectCurrentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="itemSelectPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="itemSelectTotal"
        style="margin-top: 10px;"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="itemSelectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmItemSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plan">
import { listMachinery } from "@/api/machinery/machinery";
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/plan/plan";
import { listDeviceType } from "@/api/deviceType/deviceType";
import { getCurrentInstance } from "vue";
import Checkmachinery from "@/views/checkmachinery/checkmachinery/index.vue"
import CheckSubject from "@/views/checksubject/checksubject/index.vue"

const { proxy } = getCurrentInstance()

//工单编码自动生成
import { ref } from 'vue'
const value1 = ref(false) //自动生成默认关闭
function handleChange(value) {
  if (value) {
    form.value.planCode = 'PL' + new Date().getTime()
  } else {
    form.value.planCode = ''
  }
}

// 原计划列表相关数据
const planList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const activeShow = ref(false)
// 标签页激活状态
const activeTab = ref("deviceList")

// 设备清单相关数据
const deviceTableData = ref([]) // 已选择的设备列表
const deviceCurrentPage = ref(1)
const devicePageSize = ref(10)
const deviceTotal = ref(0)
const selectedDeviceIds = ref([]) // 已选择设备的ID集合（用于批量删除）

// 保养项目相关数据
const itemTableData = ref([]) // 已选择的保养项目列表
const itemCurrentPage = ref(1)
const itemPageSize = ref(10)
const itemTotal = ref(0)
const selectedItemIds = ref([]) // 已选择保养项目的ID集合（用于批量删除）

// 设备选择弹窗相关数据
const deviceSelectDialogVisible = ref(false)
const deviceSearchForm = reactive({
  categoryName: "",
  deviceCode: "",
  deviceName: ""
})
const deviceCategoryData = ref([]) // 设备分类树形数据
const treeProps = ref({
  children: "children",
  label: "label",
  value: "machineryTypeId" // 与设备分类ID字段匹配
})
const deviceSelectTableData = ref([]) // 设备选择列表数据
const deviceSelectCurrentPage = ref(1)
const deviceSelectPageSize = ref(10)
const deviceSelectTotal = ref(0)
const selectedDevices = ref([]) // 弹窗中选中的设备（用于确认添加）

// 保养项目选择弹窗相关数据
const itemSelectDialogVisible = ref(false)
const itemSearchForm = reactive({
  itemCode: "",
  itemName: ""
})
const flag = ref(true)

const itemSelectTableData = ref([]) // 保养项目选择列表数据
const itemSelectCurrentPage = ref(1)
const itemSelectPageSize = ref(10)
const itemSelectTotal = ref(0)
const selectedItems = ref([]) // 弹窗中选中的保养项目（用于确认添加）

const data = reactive({
  form: {
    planId: null,
    planCode: null,
    planName: null,
    planType: null,
    startDate: null,
    endDate: null,
    cycleType: null,
    cycleCount: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deviceList: [], // 存储计划关联的设备ID集合（提交后端用）
    maintenanceItemList: [] // 存储计划关联的保养项目ID集合（提交后端用）
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planCode: null,
    planName: null,
    planType: null,
    cycleType: null,
    status: null,
  },
  rules: {
    planCode: [
      { required: true, message: "计划编码不能为空", trigger: "blur" }
    ],
    planName: [
      { required: true, message: "计划名称不能为空", trigger: "blur" }
    ],
    planType: [
      { required: true, message: "计划类型不能为空", trigger: "change" }
    ],
    cycleType: [
      { required: true, message: "频率不能为空", trigger: "change" }
    ],
    cycleCount: [
      { required: true, message: "频率数值不能为空", trigger: "blur" },
      { type: "number", min: 1, message: "频率数值不能小于1", trigger: "blur" }
    ],
    // startDate: [
    //   { required: true, message: "开始日期不能为空", trigger: "change" }
    // ],
    // endDate: [
    //   { required: true, message: "结束日期不能为空", trigger: "change" },
    //   { validator: validateEndDate, trigger: "change" } // 自定义结束日期校验
    // ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// ------------------------------ 基础列表逻辑 ------------------------------
/** 查询设备点检保养计划表列表 */
function getList() {
  loading.value = true
  listPlan(queryParams.value).then(response => {
    planList.value = response.rows
    total.value = response.total
    // 若编辑时已加载关联数据，切换列表时清空
    deviceTableData.value = []
    itemTableData.value = []
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 取消按钮（关闭新增/编辑弹窗）
function cancel() {
  open.value = false
  reset()
  // 清空关联数据
  deviceTableData.value = []
  itemTableData.value = []
  selectedDeviceIds.value = []
  selectedItemIds.value = []
}

// 表单重置
function reset() {
  form.value = {
    planId: null,
    planCode: null,
    planName: null,
    planType: null,
    startDate: null,
    endDate: null,
    cycleType: null,
    cycleCount: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deviceList: [],
    maintenanceItemList: []
  }
  if (proxy.$refs["planRef"]) {
    proxy.resetForm("planRef")
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  if (proxy.$refs["queryRef"]) {
    proxy.resetForm("queryRef")
  }
  handleQuery()
}

// 多选框选中数据（列表批量操作）
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.planId)
  single.value = selection.length !== 1
  multiple.value = selection.length === 0
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  activeShow.value=false

  title.value = "添加设备点检保养计划表"
}

/** 修改按钮操作（关键：返回 Promise，让 await 能等待） */
function handleUpdate(row) {
  // 1. 创建并返回 Promise 对象
  return new Promise((resolve, reject) => {
    reset()
    activeShow.value = true
    const _planId = row.planId || ids.value[0]

    // 2. 将异步请求（getPlan）包裹在 Promise 内部
    getPlan(_planId).then(response => {
      const planData = response.data
      form.value = { ...planData }
      loadPlanDevices(_planId)
      loadPlanItems(_planId)
      open.value = true
      title.value = "修改设备点检保养计划表" // 先赋值“修改标题”
      
      // 3. 异步请求成功后，调用 resolve() 通知 await“等待结束”
      resolve()
    }).catch(error => {
      proxy.$modal.msgError("加载计划详情失败")
      
      // 4. 失败时调用 reject()（可选，用于捕获错误）
      reject(error)
    })
  })
}

async function viewDetail(row){
  await handleUpdate(row)
  title.value = "查看计划信息"
  flag.value = false
}
/** 提交按钮（新增/修改计划） */
function submitForm() {
  proxy.$refs["planRef"].validate(valid => {
    if (valid) {
      // 组装关联数据（将已选择的设备/项目ID集合赋值给表单）
      form.value.deviceList = deviceTableData.value.map(item => item.deviceId)
      form.value.maintenanceItemList = itemTableData.value.map(item => item.itemId)
      
      // 验证是否选择设备和项目（根据业务需求决定是否必填）
      if (form.value.deviceList.length === 0) {
        proxy.$modal.msgWarning("请至少选择一个设备")
        return
      }
      if (form.value.maintenanceItemList.length === 0) {
        proxy.$modal.msgWarning("请至少选择一个保养项目")
        return
      }

      const request = form.value.planId ? updatePlan : addPlan
      request(form.value).then(response => {
        proxy.$modal.msgSuccess(form.value.planId ? "修改成功" : "新增成功")
        open.value = false
        getList()
        // 清空关联数据
        deviceTableData.value = []
        itemTableData.value = []
      }).catch(() => {
        proxy.$modal.msgError(form.value.planId ? "修改失败" : "新增失败")
      })
    }
  })
}

/** 删除按钮操作（列表批量删除或单行删除） */
function handleDelete(row) {
  const _planIds = row ? [row.planId] : ids.value
  if (_planIds.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的计划")
    return
  }

  proxy.$modal.confirm(`是否确认删除选中的${_planIds.length}条计划数据？`).then(() => {
    return delPlan(_planIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
    // 重置选择状态
    ids.value = []
    single.value = true
    multiple.value = true
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('plan/plan/export', {
    ...queryParams.value
  }, `设备点检保养计划_${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`)
}

// ------------------------------ 设备清单相关逻辑 ------------------------------
/** 加载计划关联的设备列表（修改时调用） */
function loadPlanDevices(planId) {
  // 假设调用接口获取计划关联的设备详情列表，此处用模拟数据示例
  // 实际项目中需替换为真实接口：listPlanDevices(planId).then(response => { ... })
  const mockDeviceData = [
    { deviceId: 1, deviceCode: "DEV001", deviceName: "步进电机机械手", brand: "明材", specModel: "BJD-6-120*H160", remark: "生产线核心设备" },
    { deviceId: 2, deviceCode: "DEV002", deviceName: "堆垛机推板", brand: "明材", specModel: "DDJ-3-200*H160", remark: "仓储辅助设备" }
  ]
  deviceTableData.value = mockDeviceData
  deviceTotal.value = mockDeviceData.length
}

/** 打开设备选择弹窗 */
function openDeviceSelectDialog() {
  deviceSelectDialogVisible.value = true
  deviceSelectCurrentPage.value = 1
  deviceSearchForm.categoryName = ""
  deviceSearchForm.deviceCode = ""
  deviceSearchForm.deviceName = ""
  // 加载设备分类树形数据
  loadDeviceCategory()
  // 加载设备选择列表
  searchDevices()
}

/** 加载设备分类树形数据 */
function loadDeviceCategory() {
  listDeviceType().then(response => {
    // 格式化分类数据为树形结构（若接口返回已格式化则直接赋值）
    deviceCategoryData.value = formatCategoryTree(response.data)
  }).catch(() => {
    proxy.$modal.msgError("加载设备分类失败")
  })
}

/** 格式化设备分类为树形结构（示例方法，根据接口返回调整） */
function formatCategoryTree(data) {
  // 假设接口返回扁平数据，需转换为父子结构
  const map = {}
  const treeData = []
  data.forEach(item => {
    map[item.machineryTypeId] = { ...item, children: [] }
  })
  data.forEach(item => {
    if (item.parentId) { // 存在父ID则添加到父节点的children
      if (map[item.parentId]) {
        map[item.parentId].children.push(map[item.machineryTypeId])
      }
    } else { // 无父ID则为根节点
      treeData.push(map[item.machineryTypeId])
    }
  })
  return treeData
}

/** 搜索设备（设备选择弹窗） */
function searchDevices() {
  const params = {
    pageNum: deviceSelectCurrentPage.value,
    pageSize: deviceSelectPageSize.value,
    equipmentCode: deviceSearchForm.deviceCode,
    equipmentName: deviceSearchForm.deviceName,
    machineryTypeId: deviceSearchForm.categoryName // 此处与树形节点value对应，根据接口调整字段名
  }
  listMachinery(params).then(response => {
    deviceSelectTableData.value = response.rows
    deviceSelectTotal.value = response.total
  }).catch(() => {
    proxy.$modal.msgError("加载设备列表失败")
  })
}

/** 重置设备搜索条件（设备选择弹窗） */
function resetDeviceSearch() {
  deviceSearchForm.categoryName = ""
  deviceSearchForm.deviceCode = ""
  deviceSearchForm.deviceName = ""
  deviceSelectCurrentPage.value = 1
  searchDevices()
}

/** 设备分类节点点击（筛选对应分类的设备） */
function handleDeviceCategoryClick(node) {
  deviceSearchForm.categoryName = node.machineryTypeId // 赋值分类ID
  deviceSelectCurrentPage.value = 1
  searchDevices()
}

/** 设备选择弹窗 - 选中设备变化 */
function handleDeviceSelectSelectionChange(selection) {
  selectedDevices.value = selection
}

/** 设备选择弹窗 - 分页大小改变 */
function handleDeviceSelectSizeChange(val) {
  deviceSelectPageSize.value = val
  deviceSelectCurrentPage.value = 1
  searchDevices()
}

/** 设备选择弹窗 - 当前页码改变 */
function handleDeviceSelectCurrentChange(val) {
  deviceSelectCurrentPage.value = val
  searchDevices()
}

/** 确认选择设备（添加到计划设备清单） */
function confirmDeviceSelection() {
  if (selectedDevices.value.length === 0) {
    proxy.$modal.msgWarning("请选择至少一个设备")
    return
  }
  // 去重逻辑（避免重复添加同一设备）
  const existingDeviceIds = deviceTableData.value.map(item => item.deviceId)
  const newDevices = selectedDevices.value.filter(item => !existingDeviceIds.includes(item.deviceId))
  if (newDevices.length === 0) {
    proxy.$modal.msgWarning("所选设备已全部添加到清单中")
    deviceSelectDialogVisible.value = false
    return
  }
  // 添加新选择的设备到清单
  deviceTableData.value = [...deviceTableData.value, ...newDevices]
  deviceTotal.value = deviceTableData.value.length
  // 关闭弹窗并重置选中状态
  deviceSelectDialogVisible.value = false
  selectedDevices.value = []
}

/** 设备清单 - 选中设备变化（用于批量删除） */
function handleDeviceSelectionChange(selection) {
  selectedDeviceIds.value = selection.map(item => item.deviceId)
}

/** 设备清单 - 分页大小改变 */
function handleDeviceSizeChange(val) {
  devicePageSize.value = val
  deviceCurrentPage.value = 1
  // 若需分页加载已选设备，需补充分页逻辑（此处简化为全量展示）
}

/** 设备清单 - 当前页码改变 */
function handleDeviceCurrentChange(val) {
  deviceCurrentPage.value = val
  // 若需分页加载已选设备，需补充分页逻辑（此处简化为全量展示）
}

/** 设备清单 - 单行删除 */
function deleteDevice(row) {
  proxy.$modal.confirm(`是否确认删除设备【${row.deviceName}】？`).then(() => {
    deviceTableData.value = deviceTableData.value.filter(item => item.deviceId !== row.deviceId)
    deviceTotal.value = deviceTableData.value.length
    // 同步更新批量选择的ID集合
    selectedDeviceIds.value = selectedDeviceIds.value.filter(id => id !== row.deviceId)
  }).catch(() => {})
}

/** 设备清单 - 批量删除 */
function deleteSelectedDevices() {
  if (selectedDeviceIds.value.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的设备")
    return
  }
  proxy.$modal.confirm(`是否确认删除选中的${selectedDeviceIds.value.length}个设备？`).then(() => {
    deviceTableData.value = deviceTableData.value.filter(item => !selectedDeviceIds.value.includes(item.deviceId))
    deviceTotal.value = deviceTableData.value.length
    // 重置批量选择状态
    selectedDeviceIds.value = []
  }).catch(() => {})
}

/** 加载计划关联的保养项目列表（修改时调用） */
function loadPlanItems(planId) {
  // 假设调用接口获取计划关联的保养项目详情列表，此处用模拟数据示例
  // 实际项目中需替换为真实接口：listPlanItems(planId).then(response => { ... })
  const mockItemData = [
    { itemId: 1, itemName: "设备清洁", itemContent: "用抹布擦拭设备表面，确保无灰尘油污", standard: "表面无可见污渍" },
    { itemId: 2, itemName: "螺丝紧固", itemContent: "检查并紧固设备各部位螺丝", standard: "无松动，扭矩达标" }
  ]
  itemTableData.value = mockItemData
  itemTotal.value = mockItemData.length
}

/** 打开保养项目选择弹窗 */
function openItemSelectDialog() {
  itemSelectDialogVisible.value = true
  itemSelectCurrentPage.value = 1
  itemSearchForm.itemCode = ""
  itemSearchForm.itemName = ""
  // 加载保养项目选择列表
  searchItems()
}

/** 搜索保养项目（项目选择弹窗） */
function searchItems() {
  const params = {
    pageNum: itemSelectCurrentPage.value,
    pageSize: itemSelectPageSize.value,
    itemCode: itemSearchForm.itemCode,
    itemName: itemSearchForm.itemName
  }
  // 假设调用接口获取保养项目列表，此处用模拟数据示例
  // 实际项目中需替换为真实接口：listMaintenanceItem(params).then(response => { ... })
  const mockItemList = [
    { itemId: 3, itemCode: "ITEM003", itemName: "润滑油添加", itemType: "常规保养", itemContent: "为设备轴承添加指定型号润滑油", standard: "油位在刻度线之间", isEnabled: true, remark: "每月一次" },
    { itemId: 4, itemCode: "ITEM004", itemName: "电路检测", itemType: "专项检测", itemContent: "检测设备电路通断及绝缘情况", standard: "绝缘电阻≥5MΩ，通路正常", isEnabled: true, remark: "每季度一次" }
  ]
  itemSelectTableData.value = mockItemList
  itemSelectTotal.value = mockItemList.length
}

/** 重置保养项目搜索条件（项目选择弹窗） */
function resetItemSearch() {
  itemSearchForm.itemCode = ""
  itemSearchForm.itemName = ""
  itemSelectCurrentPage.value = 1
  searchItems()
}

/** 保养项目选择弹窗 - 选中项目变化 */
function handleItemSelectSelectionChange(selection) {
  selectedItems.value = selection
}

/** 保养项目选择弹窗 - 分页大小改变 */
function handleItemSelectSizeChange(val) {
  itemSelectPageSize.value = val
  itemSelectCurrentPage.value = 1
  searchItems()
}

/** 保养项目选择弹窗 - 当前页码改变 */
function handleItemSelectCurrentChange(val) {
  itemSelectCurrentPage.value = val
  searchItems()
}

/** 确认选择保养项目（添加到计划保养项目清单） */
function confirmItemSelection() {
  if (selectedItems.value.length === 0) {
    proxy.$modal.msgWarning("请选择至少一个保养项目")
    return
  }
  // 去重逻辑（避免重复添加同一项目）
  const existingItemIds = itemTableData.value.map(item => item.itemId)
  const newItems = selectedItems.value.filter(item => !existingItemIds.includes(item.itemId))
  if (newItems.length === 0) {
    proxy.$modal.msgWarning("所选项目已全部添加到清单中")
    itemSelectDialogVisible.value = false
    return
  }
  // 添加新选择的项目到清单
  itemTableData.value = [...itemTableData.value, ...newItems]
  itemTotal.value = itemTableData.value.length
  // 关闭弹窗并重置选中状态
  itemSelectDialogVisible.value = false
  selectedItems.value = []
}

/** 保养项目清单 - 选中项目变化（用于批量删除） */
function handleItemSelectionChange(selection) {
  selectedItemIds.value = selection.map(item => item.itemId)
}

/** 保养项目清单 - 分页大小改变 */
function handleItemSizeChange(val) {
  itemPageSize.value = val
  itemCurrentPage.value = 1
  // 若需分页加载已选项目，需补充分页逻辑（此处简化为全量展示）
}

/** 保养项目清单 - 当前页码改变 */
function handleItemCurrentChange(val) {
  itemCurrentPage.value = val
  // 若需分页加载已选项目，需补充分页逻辑（此处简化为全量展示）
}

/** 保养项目清单 - 单行删除 */
function deleteItem(row) {
  proxy.$modal.confirm(`是否确认删除保养项目【${row.itemName}】？`).then(() => {
    itemTableData.value = itemTableData.value.filter(item => item.itemId !== row.itemId)
    itemTotal.value = itemTableData.value.length
    // 同步更新批量选择的ID集合
    selectedItemIds.value = selectedItemIds.value.filter(id => id !== row.itemId)
  }).catch(() => {})
}

/** 保养项目清单 - 批量删除 */
function deleteSelectedItems() {
  if (selectedItemIds.value.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的保养项目")
    return
  }
  proxy.$modal.confirm(`是否确认删除选中的${selectedItemIds.value.length}个保养项目？`).then(() => {
    itemTableData.value = itemTableData.value.filter(item => !selectedItemIds.value.includes(item.itemId))
    itemTotal.value = itemTableData.value.length
    // 重置批量选择状态
    selectedItemIds.value = []
  }).catch(() => {})
}

// ------------------------------ 自定义校验规则 ------------------------------
/** 结束日期校验（需晚于开始日期） */
function validateEndDate(rule, value, callback) {
  if (!value) {
    callback(new Error("结束日期不能为空"))
    return
  }
  if (form.value.startDate && new Date(value) < new Date(form.value.startDate)) {
    callback(new Error("结束日期不能早于开始日期"))
    return
  }
  callback()
}

// ------------------------------ 组件挂载时初始化 ------------------------------
onMounted(() => {
  getList()
  // 初始化时可预加载设备分类（若弹窗需要）
  // loadDeviceCategory()
})

</script>
    